package l1j.opqlo.NewSystem;

import static l1j.server.server.model.skill.L1SkillId.*;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.Config;
import l1j.server.server.serverpackets.S_Disconnect;
import l1j.server.server.serverpackets.S_NPCTalkReturn;
import l1j.server.server.GetNowTime;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.skill.L1SkillUse;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.utils.Random;
import l1j.server.server.utils.StreamUtil;

public class L1AI_Check {

	private static final Logger _log = Logger.getLogger(L1AI_Check.class.getName());
	private static final int[] _SkillList = {PHYSICAL_ENCHANT_DEX , PHYSICAL_ENCHANT_STR , BLESS_WEAPON , IMMUNE_TO_HARM , ADVANCE_SPIRIT};
//	private static final HashMap<Integer , Boolean>_checkMapId = new HashMap<Integer , Boolean>();
//	public L1AI_Check(){
//		_checkMapId.put(9901, null);
//		_checkMapId.put(9991, null);
//		_checkMapId.put(9992, null);
//		_checkMapId.put(9993, null);
//		_checkMapId.put(9994, null);
//		_checkMapId.put(9995, null);
//		_checkMapId.put(9914, null);
//		_checkMapId.put(9915, null);
//		_checkMapId.put(9916, null);
//		_checkMapId.put(9918, null);
//		_checkMapId.put(9919, null);
//		_checkMapId.put(9920, null);
//		_checkMapId.put(9921, null);
//		_checkMapId.put(9923, null);
//	}
//	
//	public static boolean checkMapId(final int mapid){
//		return _checkMapId.containsKey(mapid);
//	}

	
	public static void AI_CheckChat(final L1PcInstance pc, final String chatText) {

		if (chatText.startsWith(String.valueOf(pc.getSuper()))
				&& pc.hasSkillEffect(AI_TimeEffect)) {
			pc.killSkillEffectTimer(AI_TimeEffect);
			pc.removeSkillEffect(ABSOLUTE_BARRIER);
			pc.removeSkillEffect(SHOCK_STUN);
			pc.getMapXY();
			pc._qai = 0; // 歸零可錯誤之次數
			pc.setSuper(0);
			pc.setAICount(Random.nextInt(300) + 300);
			final String msg[] = { "隨機系統提問：", "答對了！感謝您的回答！", "現在可以關閉本視窗繼續遊戲！" };
			pc.sendPackets(new S_NPCTalkReturn(pc.getId(), "AI_Cheack3_1", msg));
			// 獎勵海賊王拉霸1次
			// pc.setSkillEffect(Laba_START,1);
			// createNewItem(pc,245174,1);
			final L1SkillUse skill = new L1SkillUse();
			for(final int skillId : _SkillList){
			skill.handleCommands(pc, skillId, pc.getId(), pc.getX(), pc.getY(), null, 0, L1SkillUse.TYPE_GMBUFF);
			}

		} else if (pc.hasSkillEffect(AI_TimeEffect)) {// 修复判斷
			if (pc._qai <= 0) {// 錯誤次數用盡 踢除玩家

//				final String msg[] = { "隨機系統提問：", "回答錯誤超過五次。", " ", "系統將您踢除下線",
//						" ", " ", " ", " ", " ", " " };
//				pc.sendPackets(new S_NPCTalkReturn(pc.getId(), "AI_Cheack21",msg));
				pc.sendPackets(new S_SystemMessage("回答錯誤超過三次系統將您踢除下線，並將記錄回報給管理人員。"));
				pc.killSkillEffectTimer(AI_TimeEffect);
				final String aa = new StringBuilder()
						.append(pc.getNetConnection().getIp().toString())
						.append(" IP ").append(pc.getName()).append("錯誤達3次斷線（")
						.append(pc.getSuper()).append("）回答：").append(chatText)
						.append("）時間: (")
						.append(new Timestamp(System.currentTimeMillis()))
						.append(")").toString();
				AI_kick(aa);
				pc.removeSkillEffect(ABSOLUTE_BARRIER);
				pc.removeSkillEffect(SHOCK_STUN);
				// TODO 使用物品記錄by opqlo
				pc.sendPackets(new S_Disconnect());
				pc.getNetConnection().close();

			} else {
				final int rndo = Random.nextInt(8999) + 1001;// 增加ranom亂數
				final String aa = new StringBuilder()
						.append(pc.getNetConnection().getIp().toString())
						.append(" IP ").append(pc.getName()).append("AI回答錯誤（")
						.append(pc.getSuper()).append("）回答：").append(chatText)
						.append("）時間: (")
						.append(new Timestamp(System.currentTimeMillis()))
						.append(")").toString();
				AI_kick(aa);
				// TODO 使用物品記錄by opqlo
				pc.setSuper(rndo);
				final String msg[] = { "隨機系統提問：",
						"剩餘次數 [ " + pc._qai + " ]，請小心做答。", " ",
						 "請輸入下方的文字", " " ,"驗證碼: A" + rndo, "",
						"超過時間會被踢下線！", " ", " " };
				pc.sendPackets(new S_NPCTalkReturn(pc.getId(), "AI_Cheack21",msg));
				pc.sendPackets(new S_SystemMessage("\\fP請再次輸入：【 A" + rndo+ " 】並按下Enter確認"));
				pc._qai--;
			}
		}
	}

	public static void AI_kick(final L1PcInstance pc) {// AI檢測 回答錯誤記錄

//		final String msg[] = { "隨機系統提問：", "超過１分鐘未完成驗證。", " ", "系統將您踢除下線",
//				"並將記錄回報給管理人員", " ", " ", " ", " ", " " };
//		pc.sendPackets(new S_NPCTalkReturn(pc.getId(), "AI_Cheack21", msg));
		pc.sendPackets(new S_SystemMessage("超過一分鐘未完成驗證系統將您踢除下線，並將記錄回報給管理人員。"));
		final String aa = new StringBuilder()
				.append(pc.getNetConnection().getIp().toString())
				.append(" IP ").append(pc.getName()).append("AI檢測無回答問題（")
				.append(pc.getSuper()).append("）時間: (")
				.append(new Timestamp(System.currentTimeMillis())).append(")")
				.toString();

		pc.killSkillEffectTimer(AI_TimeEffect);
		pc.removeSkillEffect(ABSOLUTE_BARRIER);
		pc.removeSkillEffect(SHOCK_STUN);
		pc.getNetConnection().close();

		BufferedWriter out = null;
		try {
			final String time = new StringBuilder()
					.append(GetNowTime.GetNowYear() - 2000)
					.append(GetNowTime.GetNowMonth() + 1)
					.append(GetNowTime.GetNowDay()).toString();
			out = new BufferedWriter(new FileWriter(Config.LOG_LOCATION+"記錄/AI檢測/超過時間記錄" + time
					+ ".txt", true));
			out.write(aa + "\r\n");
		} catch (final IOException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			StreamUtil.close(out);
		}
	}

	private static void AI_kick(final String info) {// AI檢測 回答錯誤記錄
		BufferedWriter out = null;
		try {
			final String time = new StringBuilder()
					.append(GetNowTime.GetNowYear() - 2000)
					.append(GetNowTime.GetNowMonth() + 1)
					.append(GetNowTime.GetNowDay()).toString();
			out = new BufferedWriter(new FileWriter(Config.LOG_LOCATION+"記錄/AI檢測/回答錯誤" + time
					+ ".txt", true));
			out.write(info + "\r\n");
		} catch (final IOException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			StreamUtil.close(out);
		}
	}
	/*
	 * private static boolean createNewItem(L1PcInstance pc, int item_id, int
	 * count) { L1ItemInstance item =
	 * ItemTable.getInstance().createItem(item_id); item.setCount(count); if
	 * (item != null) { if (pc.getInventory().checkAddItem(item, count) ==
	 * L1Inventory.OK) { pc.getInventory().storeItem(item); } else { //
	 * 持てない場合は地面に落とす 處理のキャンセルはしない（不正防止） L1World.getInstance()
	 * .getInventory(pc.getX(), pc.getY(), pc.getMapId()) .storeItem(item); }
	 * pc.sendPackets(new S_ServerMessage(403, item.getLogName())); //
	 * %0を手に入れました。 return true; } else { return false; } }
	 */
}
